#include "test14.h"
#include "ui_test14.h"
#include <QFile>
#include <QFileDialog>
#include <QTime>
#include <QTextCodec>
#include <QTextStream>
test14::test14(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::test14)
{
    ui->setupUi(this);
    initital();
}

test14::~test14()
{
    delete ui;
}

void test14::on_pushButton_clicked()
{
    QString filepath = QFileDialog::getExistingDirectory(this,"打开文件夹");
    ui->textEdit->setText(filepath);
}

void test14_file::startwrite(int time, int count, QString data, QString filename)
{
    Time = time;
    Count = count;
    Data = data;
    FileName = filename.append(".txt");
    Stopwrite(false);
    start();
}

bool test14_file::Stopwrite(bool state)
{
    mutex_stop.lock();
    flag_stop=state;
    mutex_stop.unlock();
    return true;
}

bool test14_file::test_stop()
{
    bool result=false;
    mutex_stop.lock();
    result=flag_stop;
    mutex_stop.unlock();
    return result;
}

void test14_file::run()
{
    QTime startcurrentTime = QTime::currentTime();
    QTime lastcurrentTime = startcurrentTime;
    int timeindex=1;
    QFile file(FileName);

    if(!file.open(QIODevice::WriteOnly|QIODevice::Text))
    {
        emit sig_over(1);
        return;
    }
    QTextStream out(&file);
    int i=0;
    while (!flag_stop)
    {
        QTime currentTime = QTime::currentTime();
        if(lastcurrentTime.msecsTo(currentTime)>Time)
        {
            lastcurrentTime = currentTime;
            file.write(Data.toLocal8Bit());
            file.flush();
            i++;
            emit sig_infocount(i);
        }
        int time = startcurrentTime.msecsTo(currentTime);
        if(time/100>timeindex)
        {
            timeindex++;
            emit sig_infotime(time);
        }
        if(i==Count)
            break;
    }
    emit sig_over(0);
    return;
}

void test14::on_pushButton_3_clicked()
{
    if(ui->pushButton_3->text() == "开始保存")
    {
        my_thread->startwrite(ui->spinBox->value(),ui->spinBox_2->value(),
                          ui->textEdit_2->toPlainText(),ui->textEdit->toPlainText()+"/"+ui->lineEdit->text());
        ui->pushButton_3->setText("停止保存");
    }
    else
        my_thread->Stopwrite(true);
}

void test14::slot_over(int errorinfo)
{
    if(!errorinfo)
        ui->pushButton_3->setText("开始保存");
}

void test14::initital()
{
    my_thread = new test14_file;
    connect(my_thread,&test14_file::sig_infotime,this,[=](int time)
    {
        ui->lineEdit_2->setText(QString::number(time/1000.0,'f',1));
    });
    connect(my_thread,&test14_file::sig_infocount,this,[=](int count)
    {
        ui->spinBox_3->setValue(count);
    });
    connect(my_thread,&test14_file::sig_over,this,&test14::slot_over);
}
